<?php
/**
 * User: hjd-yao
 * Date: 2018/11/5
 * Time: 16:21
 */
if(!function_exists('get_client_ip')){
    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @return mixed
     */
    function get_client_ip($type = 0)
    {

        if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }else{
            $ip = request()->getClientIp();
        }
        $ip =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        //将ip地址转换为无符号的正整数
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}

if (!function_exists('list_to_tree')) {

    /**
     * 将返回的数据集转换成树
     * @param  array   $list  数据集
     * @param  boolean   $index  索引类型
     * @param  string  $pk    主键
     * @param  string  $pid   父节点名称
     * @param  string  $child 子节点名称
     * @param  integer $root  根节点ID
     * @return array          转换后的树
     */
    function list_to_tree($list,$index=true,$pk = 'id', $pid = 'pid', $child = '_child', $root=0)
    {
        $tree = array();// 创建Tree
        if(is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =&$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    if(!$index){
                        $tree[$data[$pk]] =&$list[$key];
                    }else{
                        $tree[] =&$list[$key];
                    }

                }else{
                    if (isset($refer[$parentId])) {
                        $parent =&$refer[$parentId];
                        if(!$index){
                            $parent[$child][$data[$pk]] =&$list[$key];
                        }else{
                            $parent[$child][] =&$list[$key];
                        }
                    }
                }

            }
        }
        return $tree;
    }
}

if(!function_exists('tree_to_list')){
    /**
     * 将list_to_tree的树还原成列表
     * @param  array  $tree 原来的树
     * @param  string $child 孩子节点的键
     * @param  string $order 排序显示的键，一般是主键 升序排列
     * @param  array  $list 过渡用的中间数组，
     * @return array        返回排过序的列表数组
     * @author yangweijie <yangweijiester@gmail.com>
     */
    function tree_to_list($tree, $child = '_child', $order = 'id', &$list = array())
    {
        if (is_array($tree)) {
            $refer = array();
            foreach ($tree as $key => $value) {
                $reffer = $value;
                if (isset($reffer[$child])) {
                    unset($reffer[$child]);
                    tree_to_list($value[$child], $child, $order, $list);
                }
                $list[] = $reffer;
            }
        }
        return $list;
    }
}

if(!function_exists('get_parent_ids')){
    function get_parent_ids($list,$pk = 'id', $pid = 'pid',$root=0)
    {
        if(is_array($list)) {
            $ids = array_column($list,$pid,$pk);
            foreach ($list as $key=>$data){
               $parent_ids = [];
               $pid  = $ids[$data['id']];
               while ($pid!=$root){
                   array_push($parent_ids,$pid);
                   $pid  = isset($ids[$pid]) ? $ids[$pid] : 0;
               }
                $list[$key]['parent_ids'] = $parent_ids;
               unset($pid,$parent_ids);
            }
        }
        return $list;
    }

}

if(!function_exists('str2arr')){
    /**
     * 字符串转换为数组，主要用于把分隔符调整到第二个参数
     * @param  string $str 要分割的字符串
     * @param  string $glue 分割符
     * @param bool $strict 是否严格:true如果没有分割符也会变转变成数组，false如果没有分割符返回字符串
     * @return array
     */
    function str2arr($str,$glue = ",",$strict = true)
    {
        if(is_array($str)){
            return $str;
        }
        $search = symbol_shift($glue);
        if($search){
            $str = str_replace($search, $glue, $str);
        }
        if(!$strict&&strpos($str,$glue) === false){
            return $str;
        }
        if(in_array($glue,['|','\\','/'])){
            $pattern_glue = '\\'.$glue;
        }else{
            $pattern_glue = $glue;
        }
        $str = preg_replace("/(".$pattern_glue."+?)\\1+/is", $glue, $str);
        return array_values(array_filter(explode($glue, $str),function ($v){
            return trim($v)=='' ||strtolower($v) == 'null'||ctype_space($v)?false:true;
        }));
    }
}

if(!function_exists('arr2str')){
    function arr2str($arr, $glue = ',')
    {
        return is_array($arr)?implode($glue, $arr):$arr;
    }
}

if(!function_exists('symbol_shift')){
    /**
     * @title中英文符号切换
     * @param string $str
     * @param bool $key
     * @return mixed|Ambigous <string>
     */
    function symbol_shift($str,$key=true)
    {
        $arr = array(
            '，'=>',','：' => ':','|'=>'|',
            '－'=>'-','——'=>'-'
        );
        if($key){
            return array_keys($arr,$str);
        }else{
            return $arr[$str];
        }
    }
}


function is_json($string)
{
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

if(!function_exists('is_mobile')){
    /**
     * 判断访问设备
     * @return boolean
     */
    function is_mobile()
    {
        $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $mobile_browser = '0';
        if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i',
            strtolower($userAgent)))
            $mobile_browser++;
        if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),
                    'application/vnd.wap.xhtml+xml') !== false))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
            $mobile_browser++;
        if (isset($_SERVER['HTTP_PROFILE']))
            $mobile_browser++;
        $mobile_ua = strtolower(substr($userAgent, 0, 4));
        $mobile_agents = array(
            'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
            'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
            'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
            'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
            'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
            'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
            'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
            'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
            'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
        );
        if (in_array($mobile_ua, $mobile_agents))
            $mobile_browser++;
        if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
            $mobile_browser++;
        // Pre-final check to reset everything if the user is on Windows
        if (strpos(strtolower($userAgent), 'windows') !== false)
            $mobile_browser = 0;
        // But WP7 is also Windows, with a slightly different characteristic
        if (strpos(strtolower($userAgent), 'windows phone') !== false)
            $mobile_browser++;

        if ($mobile_browser > 0)
            return true;
        else
            return false;
    }
}

if(!function_exists('check_file_exists')){
    function check_file_exists($file)
    {

        if(empty($file)){
            return false;
        }
        if(strtolower(substr($file, 0, 4))=='http'){
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
        }else{
            return file_exists($file);
        }
    }
}

